package com.tiantian.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.tiantian.bean.PageBean;
import com.tiantian.dao.TaskGroupRepository;
import com.tiantian.dao.TaskinformationRepository;
import com.tiantian.dao.TasksOrdersRepository;
import com.tiantian.datajpa.service.impl.GenericServiceImpl;
import com.tiantian.domain.Taskgroup;
import com.tiantian.domain.Taskinformation;
import com.tiantian.domain.Tasksorders;
import com.tiantian.ret.Result;
import com.tiantian.service.BackstagelogService;
import com.tiantian.service.TaskinformationService;
import com.tiantian.util.CommonConstant.QueryType;
import com.tiantian.util.ConditionResult;

/**
 * @description 任务信息管理
 * @author ynshun
 * @sincere 2016年1月23日 下午7:04:33
 * @version 1.0
 */
@Service
public class TaskinformationServiceImpl extends GenericServiceImpl<Taskinformation, String> implements TaskinformationService {
	private TaskinformationRepository repository;
	@Autowired
	private TaskGroupRepository taskGroupRepository;
	@Autowired
	private TasksOrdersRepository tasksOrdersRepository;
	@Autowired
	private BackstagelogService backstagelogService;

	@Autowired
	public void setRepository(TaskinformationRepository repository) {
		super.setGenericDAO(repository);
		this.repository = repository;
	}

	/**
	 * 获取任务列表
	 * 
	 * @param params
	 * @param page
	 * @return
	 */
	public List<Map<String, Object>> list(Map<String, String> params, PageBean pageBean) {
		ConditionResult conditionResult = getQueryCondition(params, QueryType.LIST);
		List<Map<String, Object>> ret = repository.queryHumpListMapBySql(conditionResult.getSql(), pageBean.getStartIndex(), pageBean.getPageSize(),
				conditionResult.getParams());
		conditionResult = getQueryCondition(params, QueryType.COUNT);
		pageBean.setTotal(repository.queryCountBySql(conditionResult.getSql(), conditionResult.getParams()));
		return ret;
	}

	/**
	 * 获取导出数据
	 * 
	 * @param params
	 * @param page
	 * @return
	 */
	public List<Map<String, Object>> getReportlist(Map<String, String> params, PageBean pageBean) {
		ConditionResult conditionResult = getQueryCondition(params, QueryType.COUNT);
		pageBean.setTotal(repository.queryCountBySql(conditionResult.getSql(), conditionResult.getParams()));
		conditionResult = getQueryCondition(params, QueryType.LIST);
		List<Map<String, Object>> ret = repository.queryHumpListMapBySql(conditionResult.getSql(), 0, pageBean.getTotal().intValue(),
				conditionResult.getParams());
		return ret;
	}

	private ConditionResult getQueryCondition(Map<String, String> searchMap, QueryType type) {
		StringBuilder sql = new StringBuilder();
		Map<String, Object> params = new HashMap<String, Object>();

		switch (type) {
		case LIST:
			sql.append(" select t.*,b.StoreName ");

			break;
		case COUNT:
			sql.append(" select count(1)");
			break;
		default:
			break;
		}
		sql.append(" from TaskInformation t LEFT JOIN  BusinessStore b on b.StoreNo=t.StoreNo and b.BusinessUserID=t.BusinessUserID where 1=1 ");

		if (searchMap != null) {

			// 任务编号
			String taskId = searchMap.get("taskId");
			if (StringUtils.isNoneBlank(taskId)) {
				sql.append(" and t.taskId like :taskId ");
				params.put("taskId", "%" + taskId.trim() + "%");
			}
			// 平台
			String platformId = searchMap.get("platformId");
			if (StringUtils.isNoneBlank(platformId)) {
				sql.append(" and t.platformId=:platformId ");
				params.put("platformId", platformId.trim());
			}
			// 店铺名称
			String storename = searchMap.get("storename");
			if (StringUtils.isNoneBlank(storename)) {
				sql.append(" and b.storename like :storename ");
				params.put("storename", "%" + storename.trim() + "%");
			}
			// 终端
			String terminalId = searchMap.get("terminalId");
			if (StringUtils.isNoneBlank(terminalId)) {
				sql.append(" and t.terminalId=:terminalId ");
				params.put("terminalId", terminalId.trim());
			}

			// 任务类型
			String taskTypeId = searchMap.get("taskTypeId");
			if (StringUtils.isNoneBlank(taskTypeId)) {
				sql.append(" and t.taskTypeId=:taskTypeId ");
				params.put("taskTypeId", taskTypeId.trim());
			}
			// 任务状态
			String taskStatus = searchMap.get("taskStatus");
			if (StringUtils.isNoneBlank(taskStatus)) {
				sql.append(" and t.taskStatus=:taskStatus ");
				params.put("taskStatus", taskStatus.trim());
			}
			// 任务类型
			String businessUserId = searchMap.get("businessUserId");
			if (StringUtils.isNoneBlank(businessUserId)) {
				sql.append(" and t.businessUserId like :businessUserId ");
				params.put("businessUserId", "%" + businessUserId.trim() + "%");
			}

			// 开始时间
			String starttime = searchMap.get("starttime");
			if (StringUtils.isNoneBlank(starttime)) {
				sql.append(" and t.TaskPublishedTime>=:starttime ");
				params.put("starttime", starttime.trim());
			}
			// 结束时间
			String endtime = searchMap.get("endtime");
			if (StringUtils.isNoneBlank(endtime)) {
				sql.append(" and t.TaskPublishedTime<=:endtime ");
				params.put("endtime", endtime.trim());
			}
		}
		if (type == QueryType.LIST) {
			sql.append(" order by t.TaskPublishedTime desc");
		}
		return new ConditionResult(sql.toString(), params);

	}

	/**
	 * 获取订单统计
	 * 
	 * @param tid
	 * @return
	 */
	public List<Map<String, Object>> getOrderCount(String tid) {
		String sql = "select count(1) count,t.OrderStatus from TasksOrders t where t.TaskID=:taskId  group by t.OrderStatus  order by t.OrderStatus";
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("taskId", tid);
		return repository.queryHumpListMapBySql(sql, params);
	}

	public long getAllCount(String tid) {
		String sql = "select count(1) from TasksOrders t where t.TaskID=:taskId ";
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("taskId", tid);
		return repository.queryCountBySql(sql, params);
	}

	public List<Map<String, Object>> getSearchKeyword(String tid) {
		String sql = "select * from SearchKeyword t where t.TaskID=:taskId order by t.releaseorders";
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("taskId", tid);
		return repository.queryHumpListMapBySql(sql, params);
	}

	public Taskgroup getTaskgroup(String taskGroupNo, String businessUserID) {
		String sql = "select * from TaskGroup t where t.taskGroupNo=:taskGroupNo and t.businessUserID=:businessUserID";
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("taskGroupNo", taskGroupNo);
		params.put("businessUserID", businessUserID);
		List<Taskgroup> taskgroups = taskGroupRepository.queryListBySql(sql, params, Taskgroup.class);
		if (taskgroups != null && taskgroups.size() > 0) {
			return taskgroups.get(0);
		}
		return null;
	}

	public Result<Object> cancelOrder(String orderId) {
		Taskinformation taskinformation = this.get(orderId);
		taskinformation.setTaskStatus("3");
		taskinformation.setUndoStatus('2');
		taskinformation.setUndoApplicant("平台管理员");
		taskinformation.setUndoApplicationTime(new Date());
		this.save(taskinformation);

		List<Tasksorders> orders = tasksOrdersRepository.findByTaskIdAndOrderStatus(orderId, 1);
		if (orders != null) {
			for (Tasksorders order : orders) {
				order.setUndoApplicationTime(new Date());
				order.setUndoApplicant("1");
				order.setUndoStatus(2);
				order.setOrderStatus(8);
				tasksOrdersRepository.save(order);
			}
		}
		backstagelogService.log("02", orderId, true);
		return new Result<>(true, "订单号为" + orderId + "的未接单任务撤销成功");
	}

}
